$(function() {
//Declare variable
var  Username= $( "#txtUsername" ),
      Password=$("#txtPassword"),
            allFields = $( [] ).add( Username ).add( Password ),
            tips = $( ".validateTips" ),
            button_name="",
            url="model.php", 
            ID="",
            rowSelect=""
            param=""
            mode=1; // 0:button, 1:category
       
     // $('#panel1').jScrollPane();  
      
      reinitialiseScrollPane = function()
       {
           //alert('dd');
           $('#panel1').jScrollPane();
       }
        
       loadAll();
        
       function loadAll(){
           
            // BlockUI();
             var v = $(this).attr('id');
             param = v;
             var dataSet={'m':'search_cat','cat':v,'page':1,'pagelist':$("#cboPageList").val()};
             getData(dataSet,1,true);
             
               
       }
       //Block ui 
       function BlockUI(){
             $.blockUI({ css: { 
                border: 'none', 
                padding: '15px', 
                backgroundColor: '#000', 
                '-webkit-border-radius': '10px', 
                '-moz-border-radius': '10px', 
                opacity: .5, 
                color: '#fff' 
            } });  
           
       }
       
       //Search data 
       function getData(obj,page,b){
            //Post       
            BlockUI();  
             $.post(url,  obj , function(data){
			 
               //Remove block
             $.unblockUI();
               var obj=eval("(" + data + ")");
               
                //set data to table
                $("#content").html(obj['data']);
               
                if (obj['rows']==0){
                    $('.listpage').fadeOut(300);
                }else{
                    $('.listpage').fadeIn(900,0);
                }
				//alert(obj['totalGB']);
                $(".totalGB").html( parseFloat(obj['totalGB']).toFixed(2) );      
 
                $("#txtCurrentPage").val(page);
                $("#txtTotalPage").val(obj['totalpage']);
                $("#txtPage3").val(page + "/" + obj['totalpage']);
                
                reinitialiseScrollPane();
             });
             
                
       } 
       
      $('.next').click(function(){
            
            var p =parseInt($("#txtCurrentPage").val());
           
            if ( (p+1) <= $("#txtTotalPage").val() ){
                $("#txtCurrentPage").val(p+1);
                if (mode==1)
                    getData({'m':'search_cat','cat':param,'page':p+1,'pagelist':$("#cboPageList").val()},p+1,true);
                else
                    getData({'m':'search','name':$("#txtSearch").val(),'page':p+1,'pagelist':$("#cboPageList").val()},p+1,true);
            }
      });
      
      $('.prev').click(function(){
            var p =parseInt($("#txtCurrentPage").val());
           
            if ( (p-1) >= 1 ){
                $("#txtCurrentPage").val(p-1);
                if (mode==1)
                    getData({'m':'search_cat','cat':param,'page':p-1,'pagelist':$("#cboPageList").val()},p-1,true);
                else
                    getData({'m':'search','name':$("#txtSearch").val(),'page':p-1,'pagelist':$("#cboPageList").val()},p-1,true);                    
            }
          
      });
      
        $('.first').click(function(){
            var p =1;
            $("#txtCurrentPage").val(p);
             if (mode==1)
                getData({'m':'search_cat','cat':param,'page':p,'pagelist':$("#cboPageList").val()},p,true);
            else
                getData({'m':'search','name':$("#txtSearch").val(),'page':p,'pagelist':$("#cboPageList").val()},p,true); 
          
      });
      
       $('.last').click(function(){
            var p =parseInt($("#txtTotalPage").val());
            $("#txtCurrentPage").val(p);
             if (mode==1)
                getData({'m':'search_cat','cat':param,'page':p,'pagelist':$("#cboPageList").val()},p,true);
             else
                getData({'m':'search','name':$("#txtSearch").val(),'page':p,'pagelist':$("#cboPageList").val()},p,true); 
                    
      });
       
        //Search by Char
       $('.chr').live('click',function(){
           var val=$(this).attr('id');
           param = val;
           mode=1;
           $("#txtSearch").val('');
           getData({'m':'search_cat','cat':val,'page':1,'pagelist':$("#cboPageList").val()},1,true);
       });
       
       //Search by Category
       $('.cat').live('click',function(){
             var v = $(this).attr('id');
             param = v;
             mode=1;
             $("#txtSearch").val('');
             getData({'m':'search_cat','cat':v,'page':1,'pagelist':$("#cboPageList").val()},1,true);

       });
       
        
        $("#cboPageList").change(function(){
            if (mode==1)
                getData({'m':'search_cat','cat':param,'page':1,'pagelist':$("#cboPageList").val()},1,true);
            else
                getData({'m':'search','name':$("#txtSearch").val(),'page':1,'pagelist':$("#cboPageList").val()},1,true);
            
        });

        
        $("#btnSearch").click(function(){
            if ($("#txtSearch").val().length < 1){
                alert('กรุณากรอก ชื่อที่ต้องการค้นหา');
                $("#txtSearch").focus();
            }else{
              mode=0; 
              var vName=$("#txtSearch").val();
              getData({'m':'search','name':vName,'page':1,'pagelist':$("#cboPageList").val()},1,true);                                                   
            } 
        });
        
        
 
        function updateTips( t ) {
            tips
                .text( t )
                .addClass( "ui-state-highlight" );
            setTimeout(function() {
                tips.removeClass( "ui-state-highlight", 1500 );
            }, 500 );
        }
        function checkRegexp( o, regexp, n ) {
            if ( !( regexp.test( o.val() ) ) ) {
                o.addClass( "ui-state-error" );
                updateTips( n );
                return false;
            } else {
                return true;
            }
        }
        function checkInputFile( o, n, min ) {
            if (o.val().length < min ) {
                o.addClass( "ui-state-error" );
                updateTips( "Please input " + n + "." );
                return false;
            } else {
                return true;
            }
        }
         function checkLength( o, n, min, max ) {
            if ( o.val().length > max || o.val().length < min ) {
                o.addClass( "ui-state-error" );
                updateTips( "Length of " + n + " must be between " +
                    min + " and " + max + "." );
                return false;
            } else {
                return true;
            }
        }
        $("#paging_button li").live('click',function(){
             $("#paging_button li").css({'background-color' : ''});
           //LoadData(this.id,false);

         });     
 
         $( "#dialog:ui-dialog" ).dialog( "destroy" );
        
          $( "#dialog-form" ).dialog({
            autoOpen: false,
            height: 250,
            width: 350,
            modal: true,
            buttons: { 
                "Login": function() {
                    var bValid = true;
                    allFields.removeClass( "ui-state-error" );

                    bValid = bValid && checkInputFile( Username, "username", 1 );
                    bValid = bValid && checkInputFile( Password, "password", 1 );
                    
                    if (bValid){
                        
                         $.ajax({
                            type: 'POST',
                            cache: false,
                            url: url,
                            data: {'m':'login','u':Username.val(),'p':Password.val()},      
                            success: function(data){
                                  var obj=eval('(' + data + ')');
                                  
                                   if (obj['msg']==0){
                                       updateTips('Username & Password ไม่ถูกต้อง');
                                  }else{
                                     
                                    
                                      if (obj['confirm']=='0')
                                        window.location="index.php";
                                       else
                                         window.location="order.php";          
                                     $( "#dialog-form" ).dialog( "close" );    
                                   }             
                              }
                            });
                    }
                },
                "Register":function(){
                    window.location="register.php";                                            
                } 
            },
            close: function() {
                allFields.val( "" ).removeClass( "ui-state-error" );
            }
        });
        
    $(".btnLogout").click(function(){
         window.location="logout.php";      
    });    
    
    $(".btnLogin").click(function(){
        $( "#dialog-form" ).dialog( "open" );
    });
    
    
    $('#slides').slides({
        preload: true,
        preloadImage: 'images/loading.gif',
        play: 5000,
        pause: 2500,
        hoverPause: true
    });
    // if the function argument is given to overlay,
    // it is assumed to be the onBeforeLoad event listener
    $("a[rel]").overlay({

        mask: {
            color: '#ccc',
            loadSpeed: 200,
            opacity: 0.9
          },  
        closeOnClick: false,
        effect: 'apple',

        onBeforeLoad: function() {

            // grab wrapper element inside content
            var wrap = this.getOverlay().find(".contentWrap");

            // load the page specified in the trigger
            wrap.load(this.getTrigger().attr("href"));
        }

    });
    
    $('input[name="cboRow[]"]').live('click',function(){
        var total= $(".totalGB").html();

        var size = $(this).val();
        var id = $(this).attr('id');
    
        var name = $(this).prev().prev().attr("title");
        
        if ($(this).is(':checked')){
            var amt=(parseFloat(total) + parseFloat(size)).toFixed(2);
            $(".totalGB").html( amt );
            var data = {'m':'ac','size':size,'mid':id}
            $.post(url,  data , function(data){
                $.jGrowl("<div style='float:left'><img src='images/add2.gif' width='24px'/></div><p style='top:0;'>"+name+"<br/><font color='#FFFF33'><b>รวมขนาดไฟล์ : "+amt+"Gb.</b></font></p>",{ 
                    theme: 'smoke'              
                });
            });
            
        }else{
            var amt=(parseFloat(total) - parseFloat(size)).toFixed(2);
            $(".totalGB").html( amt );
             var data = {'m':'rc', 'mid':id}
            $.post(url,  data , function(data){
               $.jGrowl("<div style='float:left'><img src='images/remove2.gif' width='24px'/></div><p style='top:0;'>"+name+"<br/><font color='#FFFF33'><b>รวมขนาดไฟล์ : "+amt+"Gb.</b></font></p>",{ 
                    theme: 'smoke'              
                });
            });
        }
         
    });
    
       
});
    